package com.example.downloader;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import com.example.Helpers.Toasters;

/**
 * Listens for Android's BOOT_COMPLETED broadcast and then executes the
 * onReceive() method. This class also has methods for handling pending intents.
 */
public class Autostart extends BroadcastReceiver {

	private static final String TAG = "Autostart";

	/**
	 * Creating an alarm that has power to wake up the device
	 */
	public static void createAlarm(Context context) {
		Intent i = new Intent(context, DownloaderIntentService.class);
		PendingIntent pi = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		SharedPreferences settings = context.getSharedPreferences("settingPref", 0);
		am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
				Integer.parseInt(settings.getString("downloadDelay", null)), pi);
	}

	/**
	 * Checking if we have already scheduled the alarm. This is done indirectly
	 * by checking if related pending intent exists.
	 */
	public static boolean checkAlarm(Context context) {
		Intent i = new Intent(context, DownloaderIntentService.class);
		PendingIntent pi = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_NO_CREATE);
		boolean alarmUp = pi != null;
		return alarmUp;
	}

	/**
	 * Canceling the pending intent to clear related alarm
	 */
	public static void cancelAlarm(Context context) {
		Intent i = new Intent(context, DownloaderIntentService.class);
		PendingIntent pi = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
		pi.cancel();
	}

	/**
	 * Receiving notification on boot. This context we receive seems to be fully featured.
	 */
	@Override
	public void onReceive(Context context, Intent booted) {
		try {
			Log.d(TAG, "context mode isResctricted: " + context.isRestricted());
			createAlarm(context);
		} catch (Exception e) {
			Log.d(TAG, "creating alarm failed");
			Log.e(TAG, "exception", e);
			Toasters.toastEx(context, TAG, e);
		}
	}
}